﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using DevExpress.Web.Mvc;
using EnterpriseFund.Common;
using Newtonsoft.Json;
using DevExpress.Web.ASPxGridView;
using System.Web.UI;
using EnterpriseFund.BLL;
using DevExpress.XtraReports.UI;
using DevExpress.XtraPrinting;

namespace EnterpriseFund.Controllers
{
    public class QueryAllowanceInfoController : Controller
    {
        //
        // GET: /QueryAllowanceInfo/

        public ActionResult Index()
        {
            EnterpriseFund.BLL.QueryAllowanceInfo QueryAllowanceInfobll = new EnterpriseFund.BLL.QueryAllowanceInfo();
            var zsxx = QueryAllowanceInfobll.GetModelList("");
            BLL.FinanceProp f = new BLL.FinanceProp();
            var vf = f.GetAllList();
            ViewData["FinancePropList"] = vf;
            //foreach (Model.QueryAllowanceInfo x in zsxx)
            //{
            //    x.FAmount = decimal.Parse(x.FAmount.ToString()) / 10000;
            //    x.FAuditAmount = decimal.Parse(x.FAuditAmount.ToString()) / 10000;
            //    x.NeedAmount = decimal.Parse(x.NeedAmount.ToString()) / 10000;

            //}
          //  return View("Index", zsxx);
              return View("Index");
        }
        #region 导出EXCEL
        public ActionResult ExportToXls()
        {
            var table = GetData(GetFetchString());
            return GridViewExtension.ExportToXls(ExportGridViewSettings, table, HttpUtility.UrlEncode("资金拨付查询导出.xls"), true);
        }
        public ActionResult Print()
        {
            var table = GetData(GetFetchString());
            // CreatReport(table);
            return View("Print");
        }

        private void CreatReport(List<Model.QueryAllowanceInfo> table)
        {
            MVCReportGeneratonHelper generator = new MVCReportGeneratonHelper();
            generator.CustomizeColumnsCollection += new CustomizeColumnsCollectionEventHandler(generator_CustomizeColumnsCollection);
            generator.CustomizeColumn += new CustomizeColumnEventHandler(generator_CustomizeColumn);
            XtraReport report = generator.GenerateMVCReport(OperateSession.GetFromCache("QueryAllowanceInfo") as MVCxGridViewState, table);
            //  XtraReport report = generator.GenerateMVCReport(gridViewState, dt);

            //report.PaperKind = System.Drawing.Printing.PaperKind.A4;
            this.ViewData["rpt"] = report;
        }
        void generator_CustomizeColumnsCollection(object source, ColumnsCreationEventArgs e)
        {
             for (int i = 0; i < e.ColumnsInfo.Count; i++)
            {

                if (e.ColumnsInfo[i].FieldName == "NSRMC")
                {
                    e.ColumnsInfo[i].ColumnWidth = 320;
                }
                if (e.ColumnsInfo[i].FieldName == "YHZK")
                {
                    e.ColumnsInfo[i].ColumnWidth =200 ;
                }
                if (e.ColumnsInfo[i].FieldName == "KHYH")
                {
                    e.ColumnsInfo[i].ColumnWidth =320;

                }
                if (e.ColumnsInfo[i].FieldName == "FFinancePropName")
                {
                    e.ColumnsInfo[i].ColumnWidth = 100;
                }
                if (e.ColumnsInfo[i].FieldName == "FAuditAmount")
                {
                    e.ColumnsInfo[i].ColumnWidth = 150;
                }
                

            }
           
        }
        void generator_CustomizeColumn(object source, ControlCustomizationEventArgs e)
        {
            if (e.FieldName == "FAuditAmount")
            {
                //XRShape control = new XRShape();
                //control.SizeF = e.Owner.SizeF;
                //control.LocationF = new System.Drawing.PointF(0, 0);
                //e.Owner.Controls.Add(control);
                //control.Shape = new ShapeStar()
                //{
                //    StarPointCount = 5,
                //    Concavity = 30
                //};
                //control.BeforePrint += new System.Drawing.Printing.PrintEventHandler(control_BeforePrint);
                XRTableCell c = e.Owner as XRTableCell;
                c.TextAlignment = TextAlignment.MiddleRight;
                //  e.IsModified = true;
            }

           
            if (e.FieldName == "NSRMC")
            {

                XRTableCell c = e.Owner as XRTableCell;
                c.TextAlignment = TextAlignment.MiddleLeft;

            }
        }
        static GridViewSettings exportGridViewSettings;
        public static GridViewSettings ExportGridViewSettings
        {

            get
            {

                if (exportGridViewSettings == null)

                    exportGridViewSettings = CreateExportGridViewSettings();
                return exportGridViewSettings;
            }
        }
        private string IsNull(string s1, string s2)
        {
            return string.IsNullOrEmpty(s1) ? s2 : s1;
        }
        //public string ClearViewBag()
        //{
        //    try
        //    {
        //        ViewBag=null;
        //        return "OK";
        //    }
        //    catch (System.Exception ex)
        //    {
        //        return "error";
        //    }
        //}
        public ActionResult ReportViewerPartial()
        {
            var strWhere = GetWhereString();
            var zsxx = GetData(strWhere);
            MVCReportGeneratonHelper generator = new MVCReportGeneratonHelper();
            generator.CustomizeColumnsCollection += new CustomizeColumnsCollectionEventHandler(generator_CustomizeColumnsCollection);
            generator.CustomizeColumn += new CustomizeColumnEventHandler(generator_CustomizeColumn);
            XtraReport report = generator.GenerateMVCReport(OperateSession.GetFromCache("QueryAllowanceInfo") as MVCxGridViewState, zsxx);
            //  XtraReport report = generator.GenerateMVCReport(gridViewState, dt);

            //report.PaperKind = System.Drawing.Printing.PaperKind.A4;

            this.ViewData["rpt"] = report;

            return PartialView("ReportViewerPartial");

        }
        public string GetFetchString()
        {
            var nKHYH = Fetch.Post("hKHYH");
            //   var nsrbm = Request["Nsrbm"];
            var nsrmc = Fetch.Post("hnsrmc");
            var FFinance = IsNull(ComboBoxExtension.GetValue<string>("FFinance"), Fetch.Post("hFFinance"));
            //   var FAmount1 = Request["FAmount1"];
            //   var FAmount2 = Request["FAmount2"];
            var FFileNo = Fetch.Post("hFFileNo");
            //var FNote = Request["FNote"];
            //var FPayDateBegin = Request["FPayDateBegin"];
            //var FPayDateEnd = Request["FPayDateEnd"];
            var SFBF = Fetch.Post("hSFBF");
            ViewData["NKHYH"] = nKHYH;
            ViewData["NSRMC"] = nsrmc;
            ViewData["FFinance"] = FFinance;
            ViewData["FFileNo"] = FFileNo;
            ViewData["SFBF"] = SFBF;
            var filter = GetFilter(nKHYH, nsrmc, FFinance, FFileNo, SFBF);

            return filter;

        }
        public string GetWhereString()
        {
            //绑定值

            //var FTaxClassAllowanceName = IsNull(ComboBoxExtension.GetValue<string>("FTaxClassAllowanceName"), Request["FTaxClassAllowanceName"]);
            var nKHYH = Request["NKHYH"];
            //   var nsrbm = Request["Nsrbm"];
            var nsrmc = Request["Nsrmc"];
            var FFinance = IsNull(ComboBoxExtension.GetValue<string>("FFinance"), Request["FFinance"]);
            //   var FAmount1 = Request["FAmount1"];
            //   var FAmount2 = Request["FAmount2"];
            var FFileNo = Request["FFileNo"];
            //var FNote = Request["FNote"];
            //var FPayDateBegin = Request["FPayDateBegin"];
            //var FPayDateEnd = Request["FPayDateEnd"];
            var SFBF = Request["SFBF"];
            ViewBag.FFinance = FFinance;
            //ViewBag.FAmount1 = FAmount1;
            //ViewBag.FAmount2 = FAmount2;
            ViewBag.FFileNo = FFileNo;
            //   ViewBag.FNote = FNote;
            //   ViewBag.FPayDateBegin = FPayDateBegin;
            //   ViewBag.FPayDateEnd = FPayDateEnd;
            //  ViewBag.nsrbm = nsrbm;
            ViewBag.nsrmc = nsrmc;
            ViewBag.nKHYH = nKHYH;
            ViewBag.FFinance = FFinance;
            var filter = GetFilter(nKHYH, nsrmc, FFinance, FFileNo, SFBF);

            return filter;

        }

        private static string GetFilter(string nKHYH, string nsrmc, string FFinance, string FFileNo, string SFBF)
        {
            var filter = "1=1";
            if (!string.IsNullOrEmpty(SFBF) && SFBF == "true")
                filter += string.Format("and NeedAmount >0 ");
            //if (!string.IsNullOrEmpty(SFBF) && SFBF == "false")
            //    filter += string.Format("and FAuditAmount > FAmount ");
            //if (!string.IsNullOrEmpty(nsrbm))
            //    filter += string.Format("and NSRBM like '%{0}%'", nsrbm);
            if (!string.IsNullOrEmpty(nsrmc))
                filter += string.Format("and NSRMC like '%{0}%' ", nsrmc);
            if (!string.IsNullOrEmpty(nKHYH))
                filter += string.Format("and KHYH like '%{0}%' ", nKHYH);

            if (!string.IsNullOrEmpty(FFinance))
            {
                filter += string.Format(" and FFinancePropNo = '{0}' ", FFinance);
            }
            //if (!string.IsNullOrEmpty(FAmount))
            //{
            //    filter += string.Format(" and FAmount = '{0}' ", FAmount);
            //}
            //if (FAmount1 != "" && FAmount2 != "")
            //{
            //    filter += " and FAmount >=" + FAmount1 + " and FAmount<=" + FAmount2 + " ";
            //}
            //else if (FAmount1 != "")
            //{
            //    filter += " and FAmount >=" + FAmount1;
            //}
            //else if (FAmount2 != "")
            //{
            //    filter += " and FAmount <=" + FAmount2;
            //}
            if (!string.IsNullOrEmpty(FFileNo))
            {
                filter += string.Format(" and FFileNo = '{0}' ", FFileNo);
            }

            //if (!string.IsNullOrEmpty(FPayDateBegin) || !string.IsNullOrEmpty(FPayDateEnd))
            //{
            //    var begin = string.IsNullOrEmpty(FPayDateBegin) ? DateTime.MinValue.ToString() : FPayDateBegin;
            //    var end = string.IsNullOrEmpty(FPayDateEnd) ? DateTime.MaxValue.ToString() : FPayDateEnd;
            //    filter += string.Format(" AND FPayDate <= '{0}'", end);
            //    if (!string.IsNullOrEmpty(FPayDateBegin))
            //        filter += string.Format(" and FPayDate >= '{0}'", begin);
            //}
            return filter;
        }

        public List<Model.QueryAllowanceInfo> GetModelVSBZSXX()
        {
            var strWhere = GetWhereString();
            var zsxx = GetData(strWhere);
            //foreach (Model.QueryAllowanceInfo x in zsxx)
            //{
            //    x.FAmount =decimal.Parse( x.FAmount.ToString()) / 10000;
            //    x.FAuditAmount = decimal.Parse(x.FAuditAmount.ToString()) / 10000;
            //    x.NeedAmount = decimal.Parse(x.NeedAmount.ToString()) / 10000;

            //}
            return zsxx;
        }

        private static List<Model.QueryAllowanceInfo> GetData(string strWhere)
        {
            EnterpriseFund.BLL.QueryAllowanceInfo QueryAllowanceInfobll = new EnterpriseFund.BLL.QueryAllowanceInfo();
            var zsxx = QueryAllowanceInfobll.GetModelList(strWhere);
            return zsxx;
        }
        public static GridViewSettings CreateExportGridViewSettings()
        {
            var setting = new GridViewSettings();
            setting.Name = "gvEditing";
            setting.KeyFieldName = "FApplicationFormID";
            setting.CallbackRouteValues = new { Controller = "QueryAllowanceInfo", Action = "QueryAllowanceInfoListPartial" };
            setting.Width = System.Web.UI.WebControls.Unit.Percentage(100);
            setting.SettingsPager.PageSize = EnterpriseFund.Common.GlobalConstant.CONSTRING_PAGESIZE;
            //  setting.Columns.Add("NSRBM", "纳税人编码");
            setting.Columns.Add("NSRMC", "企业名称");
            setting.Columns.Add("YHZK", "银行帐号");
            setting.Columns.Add("KHYH", "开户银行");
            setting.Columns.Add("FFinancePropName", "资金性质");
            setting.Columns.Add("FAuditAmount", "补贴金额").CellStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Right;
            setting.SettingsExport.Styles.Header.BackColor = System.Drawing.Color.White;
            setting.SettingsExport.Styles.Header.ForeColor = System.Drawing.Color.Black;
            //setting.Columns.Add("FAmount", "已补助金额");
            //setting.Columns.Add("NeedAmount", "还需补助金额");
            //    setting.Columns.Add("FNote", "备注");
            setting.SettingsBehavior.AllowFocusedRow = true;
            setting.SettingsLoadingPanel.Text = "数据读取中...";
            setting.TotalSummary.Add(DevExpress.Data.SummaryItemType.Count, "NSRMC").DisplayFormat = "总计:";
            setting.TotalSummary.Add(DevExpress.Data.SummaryItemType.Sum, "FAuditAmount").DisplayFormat = "￥{0}";
            setting.GroupSummary.Add(DevExpress.Data.SummaryItemType.Sum, "FAuditAmount").DisplayFormat = "合计:￥{0}";
            //setting.TotalSummary.Add(DevExpress.Data.SummaryItemType.Sum, "FAmount").DisplayFormat = "￥{0}";
            //setting.GroupSummary.Add(DevExpress.Data.SummaryItemType.Sum, "FAmount").DisplayFormat = "合计:￥{0}";

            //setting.TotalSummary.Add(DevExpress.Data.SummaryItemType.Sum, "NeedAmount").DisplayFormat = "￥{0}";
            //setting.GroupSummary.Add(DevExpress.Data.SummaryItemType.Sum, "NeedAmount").DisplayFormat = "合计:￥{0}";
            setting.Settings.ShowGroupPanel = true;
            setting.Settings.ShowFooter = true;
            setting.ClientSideEvents.BeginCallback = "function(s,e){OnBeginCallback(s,e)}";
            setting.ClientSideEvents.EndCallback = "function(){}";

            setting.DataBinding = (sender, e) =>
            {
                ASPxGridView grid = (ASPxGridView)sender;
                for (int i = 0; i < grid.AllColumns.Count; i++)
                {
                    if (grid.AllColumns[i].HeaderStyle.HorizontalAlign == System.Web.UI.WebControls.HorizontalAlign.NotSet)
                    {
                        grid.AllColumns[i].HeaderStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;
                    }
                }
            };

            setting.SettingsBehavior.EnableCustomizationWindow = true;
			
			
            setting.PreRender = setting.BeforeGetCallbackResult = (sender, e) =>
            {


                MVCxGridView gridView = sender as MVCxGridView;
                MVCxGridViewState gridViewState = new MVCxGridViewState(gridView);
                OperateSession.SetToCache(gridViewState, "QueryAllowanceInfo");


            };

            return setting;
        }
        public ActionResult QueryAllowanceInfoListPartial()
        {
            GetWhereString();
            var vsbzsxx = GetModelVSBZSXX();
            return View(vsbzsxx);
        }
        #endregion
    }
}
